<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<script type="text/javascript">
	$(function() {
		dialogFrame = $('#user-dialog-frame').dialog({
			iconCls : 'icon-save',
			title : '对话窗口',
			resizable : true,
			closed : true,
			closable : true,
			onClose : function() {
				//当关闭对话窗口时，把所有tab一起关闭
				var allTabs = userDialogTabs.tabs('tabs');
				var closeTabsTitle = [];

				$.each(allTabs, function() {
					var opt = $(this).panel('options');
					if (opt.closable) {
						closeTabsTitle.push(opt.title);
					}
				});

				for ( var i = 0; i < closeTabsTitle.length; i++) {
					userDialogTabs.tabs('close', closeTabsTitle[i]);
				}
			}
		});

		userDialogTabsMenu = $('#user-dialog-tabsMenu').menu({
			onClick : function(item) {
				var curTabTitle = $(this).data('tabTitle');
				var type = $(item.target).attr('type');

				if (type === 'close') {
					var t = userDialogTabs.tabs('getTab', curTabTitle);
					if (t.panel('options').closable) {
						userDialogTabs.tabs('close', curTabTitle);
					}
					return;
				}

				var allTabs = userDialogTabs.tabs('tabs');
				var closeTabsTitle = [];

				$.each(allTabs, function() {
					var opt = $(this).panel('options');
					if (opt.closable && opt.title != curTabTitle && type === 'closeOther') {
						closeTabsTitle.push(opt.title);
					} else if (opt.closable && type === 'closeAll') {
						closeTabsTitle.push(opt.title);
					}
				});

				for ( var i = 0; i < closeTabsTitle.length; i++) {
					userDialogTabs.tabs('close', closeTabsTitle[i]);
				}
			}
		});

		userDialogTabs = $('#user-dialog-tabs').tabs({
			fit : true,
			border : false,
			iconCls : 'icon-edit',
			onSelect : function(title, index) {
				var tabHref = $(this).tabs('getTab', index).panel('options').href;
				var uid = tabHref.substring(tabHref.indexOf("uid=") + 4); //根据url获取到用户id
				var tabIcon = $(this).tabs('getTab', index).panel('options').iconCls;
				//获取选项卡聊天记录
				var tabMsg = $(this).tabs('getTab', index).panel('options').content;
				//图标不是edit，则更新
				if ('icon-edit' != tabIcon) {
					$(this).tabs('update', {
						tab : $(this).tabs('getTab', index),
						options : {
							iconCls : 'icon-edit',
							content : ''
						}
					});
					//更新完选项卡，把聊天记录放进去
					setMsgToViewDiv("#messageView" + uid, tabMsg);
				}
			},
			onContextMenu : function(e, title) {
				e.preventDefault();
				userDialogTabsMenu.menu('show', {
					left : e.pageX,
					top : e.pageY
				}).data('tabTitle', title);
			}
		});
		//初始化消息提示音
		notifySound = new dj.soundComponent({
			src : '${pageContext.request.contextPath}/js/notify.wav',
			altSrc : '${pageContext.request.contextPath}/js/notify.mp3'
		});
		if ('null' != '${userSession.id}' && '' != $.trim('${userSession.id}')) {
			$.ajax({
				type : "POST",
				url : "${pageContext.request.contextPath}/talkContextAction!getUnreadContext.action",
				dataType : "json",
				error : function(info) {
					eval(info.responseText);
				},
				success : function(msgs) {
					if (msgs && msgs.length > 0) {
						for ( var x = 0; x < msgs.length; x++) {
							receiveMsgFromUser(msgs[x], true);
						}
					}
				}
			});
		}
	});

	//增加对话窗口
	function addUserDialogTab(uid, name) {
		dialogFrame.dialog('open');
		if (userDialogTabs.tabs('exists', name)) {
			userDialogTabs.tabs('select', name);
		} else {
			userDialogTabs.tabs('add', {
				title : name,
				closable : true,
				href : '${pageContext.request.contextPath}/app/user/talk/dialog.jsp?uid=' + uid
			});
		}
	}

	//发送消息
	function sendMsgToUser(uid) {
		var message = $("#message" + uid);
		var messageView = $("#messageView" + uid);
		if ('' == $.trim(message.val())) {
			$('#sendInfo' + uid).html("发送内容不能为空！");
			window.setTimeout(function() {
				$('#sendInfo' + uid).html("");
			}, 2000);
			return;
		}
		//发送的消息内容
		var msgBody = message.val().replace(/\n/g, '<br />&nbsp;&nbsp;');
		//拼接消息字符串
		var msg = "<font color='green'>${userSession.name}  " + new Date().format("yyyy-MM-dd HH:mm:ss") + "</font><br><font style='font-size: 14px'>&nbsp;&nbsp;" + msgBody + "</font><br>";
		//添加到消息显示div中
		messageView.append(msg);
		//让div滚动条保持在最下面
		var scrollTop = messageView[0].scrollHeight;
		messageView.scrollTop(scrollTop);
		//dwr发送给指定用户
		MessagePush.sendMessageAuto("${userSession.id}", uid, msgBody);
		//清空输入框
		message.val("");
	}

	//接收消息,isReload参数是是否为刷新页面后加载消息
	function receiveMsgFromUser(msgJson, isReload) {
		//刷新组不为空 则刷新组
		if (msgJson.reloadGroup && !isReload) {
			var reloadGroup = $('#talk-contacts-frame').accordion("getPanel", msgJson.reloadGroup.groupname);
			if (reloadGroup) {
				reloadGroup.panel('refresh', '${pageContext.request.contextPath}/app/user/talk/friend-tree.jsp?groupid=' + msgJson.reloadGroup.id);
			}
		}
		//消息提示音
		notifySound.play();

		//显示用户消息的div
		var messageViewDiv = $("#messageView" + msgJson.sendUserid);
		//如果消息框存在，则把消息放到div中
		if (messageViewDiv[0]) {
			//消息字符串
			var msg = "<font color='blue'>" + msgJson.sendUsername + "  " + msgJson.sendTime + "</font><br><font style='font-size: 14px'>&nbsp;&nbsp;" + msgJson.msg + "</font><br>";
			//添加到消息显示div中
			messageViewDiv.append(msg);
			//非当前选中的选项卡
			if (userDialogTabs.tabs('getTab', msgJson.sendUsername) != userDialogTabs.tabs('getSelected')) {
				msg = messageViewDiv.html();

				userDialogTabs.tabs('update', {
					tab : userDialogTabs.tabs('getTab', msgJson.sendUsername),
					options : {
						iconCls : 'icon-new',
						content : msg
					//把消息放到content中，点击时放到div中显示
					}
				});

			} else {
				//让div滚动条保持在最下面
				var scrollTop = messageViewDiv[0].scrollHeight;
				messageViewDiv.scrollTop(scrollTop);
			}

			//消息设置为已读
			$.ajax({
				type : "POST",
				url : "${pageContext.request.contextPath}/talkContextAction!editReadState.action",
				data : "id=" + msgJson.id,
				error : function(info) {
					eval(info.responseText);
				}
			});
		} else {
			//否则闪烁
			//如果好友框是关闭的，并且小图标处于非闪烁状态，则小图标闪烁
			if(talkMainDialog.dialog("options").closed && !userMsgNotifyImgPre) {
				var q = 0;
				var src = "${pageContext.request.contextPath}/images/cat16.png";
				userMsgNotifyImgPre = setInterval(function() {
					var viewImg = src;
					if (q % 2 == 0) {
						viewImg = "${pageContext.request.contextPath}/images/blank16.png";
					}
					$("#user-msg-notify-img").attr("src", viewImg);
					q++;
				}, 300);
			}
			var friendGroups = msgJson.fgls;
			for ( var x = 0; x < friendGroups.length; x++) {
				deferNotify(friendGroups[x], msgJson);
			}
		}
	}

	function setWaitMsg(divId) {
		var intervalProcess = setInterval(function() {
			if ($(divId)[0]) {
				$(divId).append("<span id='loadmsg" + intervalProcess + "' style='font-size:12px'><img src='${pageContext.request.contextPath}/images/loading.gif'> 消息加载中...</span>");
				window.clearInterval(intervalProcess);
			}
		}, 300);
		return intervalProcess;
	}

	function setMsgToViewDiv(divId, msg) {
		var intervalProcess = window.setInterval(function() {
			if ($(divId)[0]) {
				$(divId).append(msg);
				//让div滚动条保持在最下面
				var scrollTop = $(divId)[0].scrollHeight;
				$(divId).scrollTop(scrollTop);
				window.clearInterval(intervalProcess);
			}
		}, 300);
	}

	//延迟加载闪烁消息
	function deferNotify(friendGroup, msgJson) {
		var friendTree = $("#user-friend-tree" + friendGroup.id);

		var deferNotifyid = setInterval(function() {
			if (!friendTree[0]) {
				friendTree = $("#user-friend-tree" + friendGroup.id);
			} else {
				//停止循环获取friendtree线程
				window.clearInterval(deferNotifyid);
				var sendUserNode = friendTree.tree('find', msgJson.sendUserid);
				if (sendUserNode) {
					//处于非闪烁状态，则闪烁
					if (!sendUserNode.attributes.intervalId) {
						//人员所在组
						var groupPanel = $('#talk-contacts-frame').accordion("getPanel", friendGroup.groupname);
						//闪烁人员
						var intervalProcess = setNotifyUser(friendTree, sendUserNode.target, msgJson.sendUsername);
						//人员通知线程id map
						var ump = notifyMap.get(friendGroup.id);
						//如果没有值，说明组没有闪烁，则闪烁组
						if (!ump || ump.size() < 1 || ump.values()[0].length < 1) {
							//组闪烁线程id
							var groupNotify = setGroupNotify(groupPanel);
							var gnMap = new Map();
							var uns = [];
							uns.push(intervalProcess);
							gnMap.put(groupNotify, uns);
							notifyMap.put(friendGroup.id, gnMap);
						} else {
							ump.values()[0].push(intervalProcess);
						}
						//把闪烁线程id放到扩张属性里面
						sendUserNode.attributes.intervalId = intervalProcess;
						//把源好友名称放到扩张属性里面，否则点击看消息的时候，还原不了标题
						sendUserNode.attributes.sourceName = msgJson.sendUsername;
						//该好友所在组，取消闪烁是用
						sendUserNode.attributes.group = friendGroup;
						//取消闪烁时，获取组用，因为组名称闪烁，不能根据组名称获取
						sendUserNode.attributes.groupIndex = $('#talk-contacts-frame').accordion('getPanelIndex', groupPanel);
					}
				}
			}
		}, 300);
	}

	//通知用户新消息，名称闪烁
	function setNotifyUser(friendTree, target, friendName) {
		var x = 0;
		var intervalProcess = setInterval(function() {
			var viewText = friendName;
			if (x % 2 == 0) {
				viewText = "";
			}
			friendTree.tree('update', {
				target : target,
				text : viewText
			});
			x++;
		}, 300);
		return intervalProcess;
	}

	function setGroupNotify(groupPanel) {
		var groupTitle = groupPanel.panel("options").title;
		var x = 0;
		var intervalProcess = setInterval(function() {
			var viewText = groupTitle;
			if (x % 2 == 0) {
				viewText = "";
			}
			groupPanel.panel('setTitle', viewText);
			x++;
		}, 300);
		return intervalProcess;
	}
</script>
<div id="user-dialog-frame" style="width:500px;height:420px;">
	<div id="user-dialog-tabs"></div>
	<div id="user-dialog-tabsMenu" style="width: 120px;display:none;">
		<div type="close">关闭</div>
		<div type="closeOther">关闭其他</div>
		<div type="closeAll">关闭所有</div>
	</div>
</div>